$(document).ready(function () {
    let currentPage = 1;
    let totalPages = 0;

    // 获取影片列表
    function fetchMovieList(query = "", page = 1) {
        $.ajax({
            url: '/api/movie/info',
            method: 'GET',
            data: {action: query ? 'query' : 'listAll', movieName: query, page: page, limit: 200},
            dataType: 'json',
            success: function (response) {
                const movies = response.data;
                const tableBody = $('#movieList');
                tableBody.empty(); // 清空现有的影片列表

                if (Array.isArray(movies)) {
                    movies.forEach(function (movie) {
                        tableBody.append(`
                            <tr>
                                <td>${movie.vod_id}</td>
                                <td>${movie.vod_name}</td>
                                <td>${movie.type_name}</td>
                                <td>${movie.vod_time}</td>
                                <td>${movie.vod_remarks}</td>
                                <td>
                                    <button class="btn btn-sm btn-error" onclick="deleteMovie(${movie.vod_id})">删除</button>
                                </td>
                            </tr>
                        `);
                    });
                } else {
                    // 处理分组数据
                    Object.keys(movies).forEach(function (typeName) {
                        const moviesByType = movies[typeName];
                        moviesByType.forEach(function (movie) {
                            tableBody.append(`
                                <tr>
                                    <td>${movie.vod_id}</td>
                                    <td>${movie.vod_name}</td>
                                    <td>${typeName}</td>
                                    <td>${movie.vod_time}</td>
                                    <td>${movie.vod_remarks}</td>
                                    <td>
                                        <button class="btn btn-sm btn-error" onclick="deleteMovie(${movie.vod_id})">删除</button>
                                    </td>
                                </tr>
                            `);
                        });
                    });
                }

                totalPages = response.totalPages;
                renderPagination(page);
            }
        });
    }

    // 编辑影片
    window.editMovie = function (vodId) {
        $.ajax({
            url: '/api/movie/info', method: 'GET', data: {action: 'query', vodId: vodId}, success: function (response) {
                if (response.code === 1) {
                    const movie = response.data;
                    $('#modalTitle').text('编辑影片');
                    $('#movieId').val(movie.vod_id);
                    $('#movieName').val(movie.vod_name);
                    $('#typeName').val(movie.type_name);
                    $('#vodTime').val(movie.vod_time);
                    $('#vodRemarks').val(movie.vod_remarks);
                    $('#modal').removeClass('hidden').addClass('modal-open');
                } else {
                    alert('获取影片信息失败: ' + response.msg);
                }
            }, error: function () {
                alert('请求失败');
            }
        });
    };

    // 提交编辑影片
    $('#submitBtn').click(function () {
        const vodId = $('#movieId').val();
        const vodName = $('#movieName').val();
        const typeName = $('#typeName').val();
        const vodTime = $('#vodTime').val();
        const vodRemarks = $('#vodRemarks').val();

        $.ajax({
            url: '/api/movie/info', method: 'PUT', data: {
                vodId: vodId, vodName: vodName, typeName: typeName, vodTime: vodTime, vodRemarks: vodRemarks
            }, success: function (response) {
                if (response.code === 1) {
                    fetchMovieList();  // 刷新影片列表
                    $('#modal').removeClass('modal-open').addClass('hidden');  // 关闭模态框
                } else {
                    alert('更新失败: ' + response.msg);
                }
            }, error: function () {
                alert('请求失败');
            }
        });
    });

    // 删除影片
    window.deleteMovie = function (vodId) {
        if (confirm('确定删除该影片吗？')) {
            $.ajax({
                url: '/api/movie/info?vodId=' + vodId, method: 'DELETE', success: function (response) {
                    if (response.code === 1) {
                        fetchMovieList();  // 刷新影片列表
                    } else {
                        alert('删除失败: ' + response.msg);
                    }
                }, error: function () {
                    alert('请求失败');
                }
            });
        }
    };

    // 搜索影片
    $('#searchBtn').click(function () {
        const query = $('#searchQuery').val();
        fetchMovieList(query, 1); // 重置到第一页
    });

    // 渲染分页按钮
    function renderPagination(page) {
        const pagination = $('#pagination');
        pagination.empty();
        for (let i = 1; i <= totalPages; i++) {
            const button = `<button class="btn ${i === page ? 'btn-active' : ''}" onclick="fetchMovieList('${$('#searchQuery').val()}', ${i})">${i}</button>`;
            pagination.append(button);
        }
    }

    // 初始加载影片列表
    fetchMovieList();
});